import 'dart:io';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class ImagePickerController {
  List<AssetEntity> selectedAssets = [];
  Future<List> uploadImg() async {
    return await dioUtil.fetchBatchUploadFile(this.selectedAssets);
  }
}

class BaseMultiImagePicker extends StatefulWidget {
  final ImagePickerController controller;
  final int maxAssets;
  const BaseMultiImagePicker({Key key, @required this.controller, this.maxAssets = 9})
      : assert(controller != null),
        super(key: key);

  @override
  _BaseMultiImagePickerState createState() => _BaseMultiImagePickerState();
}

class _BaseMultiImagePickerState extends State<BaseMultiImagePicker> {
  List<AssetEntity> get _selectedAssets => widget.controller.selectedAssets;
  set _selectedAssets(List<AssetEntity> list) {
    widget.controller.selectedAssets = list;
  }

  @override
  Widget build(BuildContext context) {
    // super.build(context);
    return FutureBuilder(
      key: UniqueKey(),
      initialData: <Widget>[],
      future: BaseUtils.filterAssetEntity<Widget>(assetEntityList: this._selectedAssets, fn: _buildSelectedImgView),
      builder: (context, snapshot) {
        List<Widget> _selectedImage = snapshot.data;
        List<Widget> _children = _selectedImage;
        if (_selectedImage.length < 9) _children.add(_buildPushImgButton());
        return Container(
          child: GridView.count(
            shrinkWrap: true,
            crossAxisSpacing: 2,
            crossAxisCount: 3,
            children: _children,
            physics: NeverScrollableScrollPhysics(),
          ),
        );
      },
    );
  }

  void _onSelectAssets() async {
    List<AssetEntity> list = await AssetPicker.pickAssets(
      context,
      selectedAssets: _selectedAssets,
      themeColor: Colors.pink,
      maxAssets: widget.maxAssets,
      pathThumbSize: 100,
      gridCount: 4,
    );

    /// 如果选择图片 直接后退不进行任何操作
    if (list != null) {
      setState(() {
        this._selectedAssets = list;
      });
    }
  }

  /// 添加图片按钮
  Widget _buildPushImgButton() {
    return BaseImageAddButton(onTap: _onSelectAssets);
  }

  /// 添加缩略图
  Widget _buildSelectedImgView(File file, int index) {
    return GestureDetector(
      child: Image.file(file, fit: BoxFit.cover),
      onTap: () async {
        var value = await BaseRouterUtil().push(BaseImgBrowseScreen(selectedAssets: this._selectedAssets, currentIndex: index));
        if (value != null) {
          setState(() {
            this._selectedAssets = value;
          });
        }
      },
    );
  }
}

class BaseImgBrowseScreen extends StatefulWidget {
  final List<AssetEntity> selectedAssets;
  final int currentIndex;
  const BaseImgBrowseScreen({Key key, @required this.selectedAssets, @required this.currentIndex}) : super(key: key);
  @override
  _BaseImgBrowseScreenState createState() => _BaseImgBrowseScreenState();
}

class _BaseImgBrowseScreenState extends State<BaseImgBrowseScreen> {
  PageController _pageController;
  int _currentIndex;
  StreamController<int> _streamController = StreamController();
  @override
  void initState() {
    _currentIndex = widget.currentIndex;
    _pageController = PageController(initialPage: _currentIndex);
    super.initState();
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        _onNavigatorPop();
        return Future.value(false);
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          title: StreamBuilder<int>(
              initialData: _currentIndex,
              stream: _streamController.stream,
              builder: (context, snapshot) {
                _currentIndex = snapshot.data;
                return Text('${snapshot.data + 1} / ${widget.selectedAssets.length == 0 ? 1 : widget.selectedAssets.length}');
              }),
          actions: [
            IconButton(
                icon: Icon(Icons.delete_outline),
                onPressed: () {
                  setState(() {
                    widget.selectedAssets.removeAt(_currentIndex);
                    if (widget.selectedAssets.length == 0) _onNavigatorPop();
                    if (_currentIndex == widget.selectedAssets.length) {
                      _currentIndex = widget.selectedAssets.length - 1;
                    }
                    _pageController.jumpToPage(_currentIndex);
                  });
                })
          ],
        ),
        body: FutureBuilder(
          future: BaseUtils.filterAssetEntity<Widget>(
            assetEntityList: widget.selectedAssets,
            fn: _buildImg,
          ),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return PageView(
                controller: _pageController,
                children: snapshot.data,
                onPageChanged: (index) {
                  _streamController.sink.add(index);
                },
              );
            } else {
              return BaseEmptyComponent();
            }
          },
        ),
      ),
    );
  }

  Widget _buildImg(file, index) {
    return Image.file(file);
  }

  void _onNavigatorPop() {
    Navigator.pop(context, widget.selectedAssets);
  }
}
